<template>
  <div>
    <!--查询参数及按钮部分-->
    <div class="filter-container">
      <el-dialog
        v-dialogDrag
        :close-on-click-modal="false"
        :title="dialogStatus"
        :visible.sync="dialogEditFormVisible"
        style="padding:0px"
        width="25%"
      >
        <el-form
          ref="dataForm"
          class="dialog-Backgroundcolor"
          :model="listQuery"
          label-position="right"
        >
          <el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="身份证号码：">
                  <el-input
                    v-model="listQuery.idenNo"
                    class="filter-item Borderwidth"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-button
              type="primary"
              style="float:right;"
              @click="handleQuery"
            >
              查询
            </el-button>

          </el-row>

        </el-form>
      </el-dialog>
    </div>
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      fit
      :height="tableHeight"
      style="width:100%;"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50"
      />
      <el-table-column v-if="tabPane === 'waitUpdate'" label="状态" align="center" width="80">
        <template slot-scope="{row}">
          <span style="float: center">{{ row.isUpdate |isUpdateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位名称"
        align="center"
      >
        <template slot-scope="{row}">
          <span style="float: left">{{ row.agencyName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="personName"
        label="姓名"
        align="center"
      />
      <el-table-column
        prop="idenNo"
        label="身份证号码"
        align="center"
      >
          <template slot-scope="{row}">
            <span style="float: left">{{ row.idenNo  }}</span>
          </template>
      </el-table-column>
      <!-- <el-table-column
        label="原开户行"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.salaCardBank | bankFilter(that) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        v-if="tabPane !== 'waitUpdate'"
        prop="newSalaCardNo"
        label="新工资卡号"
        align="center"
      /> -->
      <el-table-column
        v-if="tabPane !== 'waitUpdate'"
        label="后续操作"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.isLongUse | longUseFilter(that) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="oldSalaCardNo"
        label="原工资卡号"
        align="center"
      />
      <el-table-column
        prop="bankBackRemark"
        label="账户状态"
        align="center"
      />
      <el-table-column
        label="现姓名"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.newPersonName==row.personName?null:row.newPersonName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="新工资卡号"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ row.newSalaCardNo==row.oldSalaCardNo?null:row.newSalaCardNo }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog
      v-dialogDrag
      title="修改账户"
      :visible.sync="bankFormVisible"
      width="90%"
      max-height="500px"
    >
      <el-form
        ref="bankForm"
        :rules="bankFormRules"
        :model="formData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="人员姓名："
              prop="personName"
            >
              <el-input
                v-model="formData.personName"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="身份证号："
              prop="idenNo"
            >
              <el-input
                v-model="formData.idenNo"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="原开户行："
              prop="salaCardBank"
            >
              <el-select
                v-model="formData.salaCardBank"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  v-for="item in agencyBankLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="原工资卡账号："
              prop="oldSalaCardNo"
            >
              <el-input
                v-model="formData.oldSalaCardNo"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="现人员姓名："
              prop="newPersonName"
            >
              <el-input
                v-model="formData.newPersonName"
                
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="现身份证号："
              prop="newIdenNo"
            >
              <el-input
                v-model="formData.newIdenNo"
                
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="现开户行："
              prop="newSalaryBank"
            >
              <el-select
                v-model="formData.newSalaryBank"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  v-for="item in agencyBankLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="现工资卡账号："
              prop="newSalaCardNo"
            >
              <el-input
                v-model="formData.newSalaCardNo"
                maxlength="60"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col style="margin-left:10%; margin-top:20px; ">
            <el-radio
              v-model="formData.isLongUse"
              :label="0"
            >仅供发放本月工资
            </el-radio>
            <el-radio
              v-model="formData.isLongUse"
              :label="1"
            >替换原卡长期使用该卡发放工资
            </el-radio>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col class="bankTips">
            <span>注意：新工资卡必须与原工资卡是同一银行</span><br>
            <!-- <span>1）新工资卡必须在原开户行开户。</span><br> -->
            <!-- <span>2）当选择仅供发放本月工资使用时，该新卡号只在为发放本月工资。</span><br>
            <span>3）当选择长期使用时，将自动在人员信息中更新为工资卡信息为新卡。</span><br> -->
          </el-col>
        </el-row>
        <el-row style="padding-top:5%">
          <el-col
            :span="24"
            style="text-align:center"
          >
            <el-button
              round
              type="primary"
              :loading="saveNewBankLoading"
              @click="saveNewBank"
            >
              保存
            </el-button>
            <el-button
              round
              @click="bankFormVisible = false"
            >
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <file ref="fileRef" :middle-table-code="2" />
    </el-dialog>
  </div>
</template>

<script>
import file from '@/views/personInfoMaintenance/children/file'
import { getSex, getAgencyBank,  getConfigCtrlByTypeMof } from '@/api/baseInfo'
import {
  querySalaryBankPayBackSendPage,
  updateBankInfo,
  revokeUpdate,
  verifyPass,
  revokeVerify,
  sendVerifyFinance,
  revokeVerifyFinance
} from '@/api/exceptionCardNumberManage/unitEditCardNumber'
import { updatePersonnelCardNumberFiscal } from '@/api/exceptionCardNumberManage/cardNumberFinancialProcess'
import Pagination from '@/components/Pagination'
import tableEmpty from '@/components/table/empty'

export default {
  name: 'UnitEditCardNumber',
  components: { Pagination, tableEmpty, file },
  filters: {
    bankFilter(type, that) {
      const agencyBankLists = that.agencyBankLists
      for (const item in agencyBankLists) {
        if (agencyBankLists[item].code === type) {
          return agencyBankLists[item].name
        }
      }
    },
    sexFilter(type, that) {
      const sexLists = that.sexLists
      for (const item in sexLists) {
        if (sexLists[item].code === type) {
          return sexLists[item].name
        }
      }
    },
    longUseFilter(type, that) {
      if (type === 0) {
        return '本月使用'
      } else if (type === 1) {
        return '长期使用'
      }
    },
    isUpdateFilter(type, that) {
      if (type === 0) {
        return '未修改'
      } else if (type === 1) {
        return '已修改'
      }
    },
    //号码脱敏显示
    hideMiddle(val) {
      if(val!== undefined&& val!== null){//避免列表中存在空数据报错
        return `${val.substring(0,4)}****${val.substring(val.length-4)}`
      }else{
        return val
      }
    }
  },
  props: ['tabPane', 'treeData'],
  data() {
    return {
      tableHeight: null,
      dialogEditFormVisible: false,
      saveNewBankLoading: false,
      dialogStatus: '',
      that: this,
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 200,
        flag: 'waitUpdate',
        idenNo: '',
        agencyId: ''
      },
      formData: {
        personName: '',
        idenNo: '',
        salaCardBank: '',
        newPersonName: '',
        newIdenNo: '',
        newSalaryBank: '',
        oldSalaCardNo: '',
        newSalaCardNo: '',
        isLongUse: '0',
        agencyId: '',
        personId: ''
      },
      sexLists: [],
      agencyBankLists: [],
      bankFormVisible: false,
      bankFormRules: {
        newSalaCardNo: [
          { required: true, message: '请输入新工资卡账号', trigger: 'blur' },
          {
            pattern: /^([1-9]{1})(\d{14}|\d{15}|\d{16}|\d{17}|\d{18})$/,
            message: '请输入正确的银行卡号',
            trigger: 'blur'
          }
        ],
         newPersonName: [{ required: true, message: '请输入现姓名', trigger: 'blur' }],
        newIdenNo: [
          { required: true, message: '请输入身份证号码', trigger: 'blur' },
          {
            pattern:/((^[1-9]\d{5}(18|19|([23]\d))\d{2}(((0[13578]|10|12)(0[1-9]|[12]\d|3[01]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[12]\d)))\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}(((0[13578]|10|12)(0[1-9]|[12]\d|3[01]))|((0[469]|11)(0[1-9]|[12]\d|30))|(02(0[1-9]|[12]\d)))\d{3}$))|(^[\u4E00-\u9FA5](字第)([0-9a-zA-Z]{4,10})(号?)$)/,
            message: '证件号码格式有误！',
            trigger: 'blur'
          }
        ],
        newSalaryBank: [{ required: true, message: '请输入现银行', trigger: 'blur' }],
      },
      revokePersonLists: []
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    },
    treeData(val) {
      if (val && val.isleaf === '1') {
        this.listQuery.agencyId = val.id
        this.formData.agencyId = val.id
        this.handleTree(val)
      }
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  created() {
    this.listQuery.flag = this.tabPane
    this.initBaseInfo()
    if (this.treeData && this.treeData.isleaf === '1') {
      this.listQuery.agencyId = this.treeData.id
      this.formData.agencyId = this.treeData.id
      this.listQuery.page = 1
      this.getList()
    }
  },
  methods: {
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 更新人事信息
    updatePersonnel() {
      if (this.list.length === 0) {
        this.$message({
          showClose: true,
          message: '暂无数据，不能更新',
          type: 'warning',
          duration: 4000
        })
        this.$emit('PersonnelCallBack')
        return
      }

      // 提示框确认
      // this.$confirm('确定更新人事信息吗？', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      updatePersonnelCardNumberFiscal(this.listQuery).then(response => {
        this.$message({
          showClose: true,
          message: '更新人事信息成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('PersonnelCallBack')
        // 更新
        this.handleQuery()
        // })
      }).catch(() => {
        this.$emit('PersonnelCallBack')
      })
    },
    getTbHeight() {
      this.tableHeight = window.innerHeight - 223
    },
    getList() {
      this.listLoading = true
      querySalaryBankPayBackSendPage(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    restTemplate() {
      this.formData = {
        personName: '',
        idenNo: '',
        salaCardBank: '',
        oldSalaCardNo: '',
        newSalaCardNo: '',
        isLongUse: '0',
        agencyId: this.listQuery.agencyId
      }
    },
    updateBank() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.formData = Object.assign({}, this.formData, selection[0])
      setTimeout(() => {
        this.$refs.fileRef.clear_tmp_list(this.formData.personId, this.formData.agencyId)
        // this.$refs[refForm].clearValidate()
      }, 1000)
      this.bankFormVisible = true
    },
    async saveNewBank() {
      const file_list = await this.$refs.fileRef.attachmentPreservation(this.formData.personId, this.formData.agencyId) // 获取真的附件列表，判断是否为空
      const tmp_list = await this.$refs.fileRef.get_tmp_list() // 获取假的附件列表，判断是否为空
      if ((file_list && file_list.length === 0) && (tmp_list && tmp_list.length === 0)&&this.configCtrl=='1') {
        this.$message({
          message: '请上传附件！',
          type: 'warning'
        })
        return
      }
      this.$refs['bankForm'].validate(valid => {
        if (valid) {
          if (this.formData.personName === this.formData.newPersonName && this.formData.idenNo === this.formData.newIdenNo && this.formData.salaCardBank === this.formData.newSalaryBank && this.formData.oldSalaCardNo === this.formData.newSalaCardNo){
             this.$message({
              showClose: true,
              message: '未修改任何信息！请确认',
              type: 'warning',
              duration: 4000
            })
            return
          }
          this.saveNewBankLoading = true
          const tempData = Object.assign({}, this.formData)
          updateBankInfo(tempData).then(response => {
            this.bankFormVisible = false
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success',
              duration: 4000
            })
             this.$refs.fileRef.save() // 第三个页签保存
            this.saveNewBankLoading = false
            this.handleQuery()
          }).catch(() => {
          this.saveNewBankLoading = false
        })
        }
      })
    },
    revokeUpdate() {
      this.revokePersonLists = []
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要撤销修改的人员',
          type: 'warning',
          duration: 4000
        })
        this.$emit('isRevokeUpdateCallBack')
        return
      }
      selection.forEach(item => {
        this.revokePersonLists.push(item)
      })
      // this.$confirm('确定撤销修改吗?', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      revokeUpdate(this.revokePersonLists).then(response => {
        this.$message({
          showClose: true,
          message: '撤销修改成功',
          type: 'success',
          duration: 4000
        })
        this.$emit('isRevokeUpdateCallBack')
        this.handleQuery()
        // })
      })
        .catch(() => {
          this.$emit('isRevokeUpdateCallBack')
        })
    },
    verifyPass() {
      this.restTemplate()
      // this.$confirm('确定审核通过吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      verifyPass(this.formData).then(response => {
        if (response.data === '500') {
          this.$message({
            showClose: true,
            message: '存在未修改的卡号，不允许审核',
            type: 'warning',
            duration: 4000
          })
          this.$emit('isVerifyPassCallBack')
        } else if (response.data === '200') {
          this.$message({
            showClose: true,
            message: '审核通过成功',
            type: 'success',
            duration: 4000
          })
          this.$emit('isVerifyPassCallBack')
        }
        this.handleQuery()
        // })
      })
        .catch(() => {
          this.$emit('isVerifyPassCallBack')
        })
    },
    revokeVerify() {
      this.restTemplate()
      // this.$confirm('确定撤销审核吗?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      revokeVerify(this.formData).then(response => {
        if (response.data === '500') {
          this.$message({
            showClose: true,
            message: '异常卡号已送审财政，不允许撤销操作',
            type: 'warning',
            duration: 4000
          })
          this.$emit('isRevokeVerifyCallBack')
        } else if (response.data === '501') {
          this.$message({
            showClose: true,
            message: '单位未审核通过，不允许撤销操作',
            type: 'warning',
            duration: 4000
          })
          this.$emit('isRevokeVerifyCallBack')
        } else if (response.data === '200') {
          this.$message({
            showClose: true,
            message: '撤销审核成功',
            type: 'success',
            duration: 4000
          })
          this.$emit('isRevokeVerifyCallBack')
        }
        this.handleQuery()
        // })
      })
        .catch(() => {
          this.$emit('isRevokeVerifyCallBack')
        })
    },
    sendVerifyFinance() {
      this.restTemplate()
      // this.$confirm('确定送审财政吗?', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      sendVerifyFinance(this.formData).then(response => {
        if (response.data === '500') {
          this.$message({
            showClose: true,
            message: '单位未审核通过，不允许财政送审',
            type: 'warning',
            duration: 4000
          })
          this.$emit('isSendVerifyFinanceCallBack')
        } else if (response.data === '200') {
          this.$message({
            showClose: true,
            message: '送审财政成功',
            type: 'success',
            duration: 4000
          })
          this.$emit('isSendVerifyFinanceCallBack')
        }
        this.handleQuery()
        //  })
      })
        .catch(() => {
          this.$emit('isSendVerifyFinanceCallBack')
        })
    },
    revokeVerifyFinance() {
      this.restTemplate()
      this.$confirm('确定撤销送审吗?', '提示', {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          revokeVerifyFinance(this.formData).then(response => {
            if (response.data === '500') {
              this.$message({
                showClose: true,
                message: '财政已确认，不允许撤销财政送审',
                type: 'warning',
                duration: 4000
              })
              this.$emit('isRevokeVerifyFinanceCallBack')
            } else if (response.data === '501') {
              this.$message({
                showClose: true,
                message: '单位未审核通过，不允许撤销财政送审',
                type: 'warning',
                duration: 4000
              })
              this.$emit('isRevokeVerifyFinanceCallBack')
            } else if (response.data === '200') {
              this.$message({
                showClose: true,
                message: '撤销送审成功',
                type: 'success',
                duration: 4000
              })
              this.$emit('isRevokeVerifyFinanceCallBack')
            }
            this.handleQuery()
          })
        })
        .catch(() => {
          this.$emit('isRevokeVerifyFinanceCallBack')
        })
    },

    initBaseInfo() {
      getSex().then(response => {
        this.sexLists = Object.assign({}, response.data)
      })
      getAgencyBank().then(response => {
        this.agencyBankLists = Object.assign({}, response.data)
      })
       getConfigCtrlByTypeMof("fileVerify").then(response => {
        this.configCtrl = response.data
        
      })
    },
    query() {
      this.dialogStatus = '查询'
      this.dialogEditFormVisible = true
    },
    handleQuery() {
      this.dialogStatus = '单位编辑卡号查询'
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
      this.dialogEditFormVisible = false
    },
    handleTree(data) {
      this.listQuery.page = 1
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.bankTips {
  padding-top: 5%;

  span:nth-child(1) {
    margin-left: 2%;
  }

  span:not(:nth-child(1)) {
    margin-left: 5%;
  }

  span {
    font-size: 16px;
    color: red;
  }
}
</style>
